import axios from 'axios'
import { useUserStore } from '@/stores'

const instance = axios.create({
    timeout: 50000
})
//设置请求拦截器
instance.interceptors.request.use(
    (config) => {
        //携带token
        const userStore = useUserStore()
        if (userStore.token) {
            config.headers.token = userStore.token
        }
        return config
    },
    (err) => Promise.reject(err)
)

//设置响应拦截器
instance.interceptors.response.use(
    (res) => {
        //摘取核心响应数据
        if (res.status === 200){
          return res.data
        }

        //处理业务失败
        ElMessage.error(res.data.msg || '服务器异常')
        return Promise.reject(res)
    },

    (err) => {
        alert(err.msg || '服务器异常')
        return Promise.reject(err)
    }
)

export default instance
